import os
import socket
import subprocess
import datetime
import smtplib
import logging
from ping3 import ping
from email.mime.text import MIMEText
from apscheduler.schedulers.blocking import BlockingScheduler


gNetworkDownCount = 0
gIPList = ['www.baidu.com', 'www.taobao.com', '52.80.130.73']		# amazon bj1


def PingHost(ip):
	result = ping(ip)
	if result is not None and result is not False:
		delay = int(result * 1000)
		print(ip, '\t', delay, "ms")
		logging.info('ping '+ip+'\t time: '+str(delay)+' ms')
		return True
	else:
		print('ping failed: '+ip)
		logging.warning('ping failed: '+ip)
		return False

def ShutDown():
	print('Shutting down server')
	logging.warning(
		'\n############################################################'
		'\n############### ping failed 4 min, shut down server #################'
		'\n############################################################')
	os.popen('shutdown -s -t 10')

def CheckNetwork():
	global gNetworkDownCount

	print('\n', datetime.datetime.now())
	pingFailedCount = 0
	for ip in gIPList:
		if PingHost(ip) == False:
			pingFailedCount += 1
		else:
			gNetworkDownCount = 0

	if pingFailedCount == 3:
		gNetworkDownCount += 1

	if gNetworkDownCount == 4:
		ShutDown()


if __name__ == '__main__':
	# set logging config
	logging.basicConfig(
		filename='auto_shutdown.log', 
		format='%(asctime)s-%(levelname)s:  %(message)s',
		level = logging.INFO,
		filemode='a',
		datefmt='%Y-%m-%d%I:%M:%S %p')
	logging.getLogger('apscheduler').setLevel(logging.WARN)
	logging.info('\n\n              Auto ShutDown Started \n')

	cTime = datetime.datetime.now()
	scheduler = BlockingScheduler()
	scheduler.add_job(CheckNetwork, 'interval', misfire_grace_time=3, seconds=60, id='CheckNetwork', next_run_time=cTime)
	scheduler.start()